package cn.huiyunche.base.service.utils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ExcelExport {

    /**
     * 导出之前调用此方法
     */
    public static HttpServletResponse exprotBefore(HttpServletRequest request,
                                                   HttpServletResponse response, String excelName) {
        HttpSession session = request.getSession();
        session.setAttribute("state", null);
        // 生成提示信息，
        response.setContentType("application/vnd.ms-excel");
        try {
            excelName = java.net.URLEncoder.encode(excelName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        excelName = excelName + getDate() + "导出数据.xlsx";
//			response.setHeader("content-disposition", "attachment;filename="+excelName);
        response.setHeader("content-disposition", "attachment");
        response.setHeader("x-filename", excelName);
        return response;
    }

    /*
    * 列数据信息单元格样式
    */
    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        // font.setFontHeightInPoints((short)10);
        // 字体加粗
        // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在样式用应用设置的字体;
        style.setFont(font);
        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;
    }

    /*
    * 列头单元格样式
    */
    public static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        font.setFontHeightInPoints((short) 11);
        // 字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在样式用应用设置的字体;
        style.setFont(font);
        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;
    }

    /**
     * 导出的方法
     */
    @SuppressWarnings("deprecation")
    public static HSSFWorkbook export(String fileName, String[] titile,
                                      List<String[]> listData, int[] columnWidth, Boolean[] isdigit, String titleName) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        try {
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet(fileName);

            // 产生表格标题行
            HSSFRow rowm = sheet.createRow(0);
            HSSFCell cellTiltle = rowm.createCell(0);

            //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面  - 可扩展】  
            HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);//获取列头样式对象  
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (titile.length - 1)));
            cellTiltle.setCellStyle(columnTopStyle);
            cellTiltle.setCellValue(titleName);

            int columnNumber = titile.length;
            //第一行标题
            Row row0 = sheet.createRow(2);
            //设置居中的样式
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(CellStyle.ALIGN_CENTER);
            for (int i = 0; i < columnNumber; i++) {
                Cell c0 = row0.createCell(i);
                //设置列宽度
                sheet.setColumnWidth(i, columnWidth[i] * 100);
                c0.setCellStyle(style);
                c0.setCellValue(titile[i]);
            }
            //第二行和后面的
            int listSize = listData.size();
            for (int m = 0; m < listSize; m++) {
                String[] s = listData.get(m);
                Row row = sheet.createRow(m + 3);
                for (int n = 0; n < columnNumber; n++) {
                    Cell cell = row.createCell(n);
                    if (s[n] != null) {
                        if (isdigit != null &&
                                isdigit[n] != null &&
                                isdigit[n]) {
                            cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                            try {
                                cell.setCellValue(Double.valueOf(s[n]));
                            } catch (Exception e) {
                                e.getMessage();
                            }

                        } else {
                            cell.setCellValue(s[n]);
                        }
                    }
                }
            }
        } catch (Exception e) {
            workbook.close();
            e.printStackTrace();
        }
        workbook.close();
        return workbook;
    }

    /**
     * 导出的方法
     */
    @SuppressWarnings("deprecation")
    public static HSSFWorkbook billExport(String[] titile, int[] columnWidth, Boolean[] isdigit, String titleName, Map<String, Object> map) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        try {
            for (String fileName : map.keySet()) {
                // 生成一个表格
                HSSFSheet sheet = workbook.createSheet(fileName);

                @SuppressWarnings("unchecked")
                List<String[]> listData = (List<String[]>) map.get(fileName);
                // 产生表格标题行
                HSSFRow rowm = sheet.createRow(0);
                HSSFCell cellTiltle = rowm.createCell(0);

                //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面  - 可扩展】
                HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);//获取列头样式对象
                sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (titile.length - 1)));
                cellTiltle.setCellStyle(columnTopStyle);
                cellTiltle.setCellValue(titleName);

                int columnNumber = titile.length;
                //第一行标题
                Row row0 = sheet.createRow(2);
                //设置居中的样式
                CellStyle style = workbook.createCellStyle();
                style.setAlignment(CellStyle.ALIGN_CENTER);
                for (int i = 0; i < columnNumber; i++) {
                    Cell c0 = row0.createCell(i);
                    //设置列宽度
                    sheet.setColumnWidth(i, columnWidth[i] * 100);
                    c0.setCellStyle(style);
                    c0.setCellValue(titile[i]);
                }
                //第二行和后面的
                int listSize = listData.size();
                for (int m = 0; m < listSize; m++) {
                    String[] s = listData.get(m);
                    Row row = sheet.createRow(m + 3);
                    for (int n = 0; n < columnNumber; n++) {
                        Cell cell = row.createCell(n);
                        if (s[n] != null) {
                            if (isdigit != null &&
                                    isdigit[n] != null &&
                                    isdigit[n]) {
                                cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                                try {
                                    cell.setCellValue(Double.valueOf(s[n]));
                                } catch (Exception e) {
                                    e.getMessage();
                                }

                            } else {
                                cell.setCellValue(s[n]);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            workbook.close();
            e.printStackTrace();
        }
        workbook.close();
        return workbook;
    }

    private static String getDate() {
        // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("[yyyy-MM-dd]");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

}